package com.cd.university.common.utils;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

/**
 * 一个单列的生成CountDownLatch的类
 * @author 陈栋
 * @create 2021/12/17 10:07
 */
public class CountDownLatchMap {

    /**
     * key为项目的id，value为CountDownLatch计数器
     */
    private ConcurrentHashMap<Integer, CountDownLatch> latchMap = new ConcurrentHashMap<>();

    private static CountDownLatchMap instance;

    private CountDownLatchMap() {
    }

    public static CountDownLatchMap newInstance() {
        if (instance==null) {
            synchronized (ConcurrentHashMap.class) {
                if (instance==null) {
                    instance = new CountDownLatchMap();
                }
            }
        }
        return instance;
    }

    /**
     * 生成一个CountDownLatch
     * @param projectId 项目id
     * @param count 计数个数
     * @return CountDownLatch
     */
    public CountDownLatch getSafeLatch(Integer projectId,int count) {
        CountDownLatch latch;
        if ((latch = latchMap.get(projectId))==null) {
            synchronized (CountDownLatchMap.class) {
                if (latch==null) {
                    latch = new CountDownLatch(count);
                    latchMap.put(projectId, latch);
                }
            }
        }

        return latch;
    }

    public void removeLatch(Integer projectId) {
        latchMap.remove(projectId);
    }
}
